﻿using System.IO;

using NUnit.Framework;
using LuaInterface;

namespace System.Lua.Tests
{
    [TestFixture]
    public class LuaReaderTest
    {
        [Test]
        public void IsVariableDefinedTest()
        {
            const string lua = "message = 'Hello from Lua!'";

            using (var textReader = new StringReader(lua))
            using (LuaReader luaReader = LuaReader.Create(textReader))
            {
                Assert.IsFalse(luaReader.IsVariableDefined("foo"));
                Assert.IsTrue(luaReader.IsVariableDefined("message"));
            }
        }

        [Test]
        public void GetStringVariableValueTest()
        {
            const string lua = "message = 'Hello from Lua!'";

            using (var textReader = new StringReader(lua))
            using (LuaReader luaReader = LuaReader.Create(textReader))
            {
                Assert.IsTrue(luaReader.IsVariableDefined("message"));
                Assert.AreEqual("Hello from Lua!", luaReader["message"]);
            }
        }

        [Test]
        public void GetTableVariableValueTest()
        {
            const string lua = "table = { message = 'Hello from Lua!'}";

            using (var textReader = new StringReader(lua))
            using (LuaReader luaReader = LuaReader.Create(textReader))
            {
                Assert.IsTrue(luaReader.IsVariableDefined("table"));
                Assert.IsTrue(luaReader["table"] is LuaTable);
                Assert.AreEqual("Hello from Lua!", ((LuaTable)luaReader["table"])["message"]);
            }
        }

        [Test]
        public void VariableCountTest()
        {
            const string lua = "message = 'Hello from Lua!'";

            using (var textReader = new StringReader(lua))
            using (LuaReader luaReader = LuaReader.Create(textReader))
            {
                Assert.AreEqual(1, luaReader.VariableCount);
            }
        }

        [Test]
        [ExpectedException(typeof(CouldNotInterpretException))]
        public void UndefinedFunctionCallTest()
        {
            const string lua = "foo()";

            using (var textReader = new StringReader(lua))
            {
                LuaReader.Create(textReader).Dispose();
            }
        }

        [Test]
        public void GlobalFunctionsUnavailableTest()
        {
            using (LuaReader luaReader = LuaReader.Create())
            {
                Assert.IsNull(luaReader["print"]);
            }
        }

        [Test]
        [ExpectedException(typeof(CouldNotInterpretException))]
        public void CannotInterpretStandardLibraryCallTest()
        {
            const string lua = "print('this is a built in function')";

            using (var textReader = new StringReader(lua))
            {
                LuaReader.Create(textReader).Dispose();
            }
        }
    }
}
